Functions
Learn about functions in Go.
defer statement#
defer statement doesn’t seem to have big traps, but it’s worth mentioning a few
nuances.
From an excellent post by Andrew Gerrand on the subject:
Note: A
deferstatement pushes a function call onto a list. The list of saved calls is executed after the surrounding function returns.deferis commonly used to simplify functions that perform various cleanup actions.
The most important points to be aware of:
1. Evaluation of arguments#
While a deferred function is invoked when the original function returns, its arguments are evaluated at the point of calling defer.
2.Execution order#
Deferred functions execute in Last In First Out order once the original function returns.
Running the above code will reverse the order of input values.
3. Access#
Deferred functions can access and modify named function arguments.
4. Scope#
defer doesn’t work for code blocks, only for the whole function.
Unlike variable declarations, defer statements are not scoped to code
blocks:
In this example, a deferred function call will be added to the list when i is 0, 3, and 6. But it will only get invoked when the main function exits and not at the end of the if statement.
5. recover() in deferred functions#
recover() only works inside of deferred functions, it will do nothing in the original function.
It doesn’t really make sense any other way, but in case you’re looking for an equivalent of try…catch statements, there are none in Go. Panics are caught using recover() inside of deferred functions.
Quiz: Control Structures
Goroutines